﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Xml.Linq;
using Ninject;

namespace InstantWatch {
	public class RssProxy : AProxy {

		[Inject]
		public RssSettings Settings { get; set; }

		#region IProxy Members

		public override IEnumerable<QueueItem> GetUserQueue(int count) {
			string xml;
			using (WebClient wc = new WebClient()) {
				xml = wc.DownloadString(Settings.Url);
			}

			XElement queue = XElement.Parse(xml);

			var items = from q in queue.Descendants("item")
									select
									ParseItem(q);
			return items;
		}

		#endregion

		public static QueueItem ParseItem(XElement xml) {

			QueueItem item = new QueueItem();

			item.Name = xml.Descendants("title").First().Value;
			item.Id = "hulu - " + item.Name;

			item.BoxArtFile = @"..\boxArt\tempBoxArt.jpg";
			item.BoxArtSource = xml.Descendants(@"{http://search.yahoo.com/mrss/}thumbnail").First().Attribute("url").Value;

			item.SynopsisSource = GetDescription(xml);

			item.WatchLink = xml.Descendants("link").First().Value;

			int lastIndex = item.BoxArtSource.LastIndexOf(@"/");
			string destinationPath = Path.Combine(@"boxArt\hulu\", item.BoxArtSource.Substring(lastIndex + 1));
			destinationPath = GetBoxArt(item.BoxArtSource, destinationPath);
			item.BoxArtFile = destinationPath;


			return item;
		}

		private static string GetDescription(XElement xml) {
			/* Sample string
<a href=\"http://www.hulu.com/watch/24252/highlander-not-to-be#http%3A%2F%2Fwww.hulu.com%2Ffeed%2Fqueue%2Fjquintus;play-queue\">
<img src=\"http://thumbnails.hulu.com/8/977/26552_145x80_manicured__Nd6WCUO7fkuKJZ6k8kDouw.jpg\" align=\"right\" hspace=\"10\" vspace=\"10\" width=\"145\" height=\"80\" border=\"0\" />
</a>
<p>Alongside Fitz, Duncan takes the conclusions of what life would be without him.</p>
<p>
<a href=\"http://www.hulu.com/users/add_to_playlist?from=feed&video_id=24252\">Add this to your queue</a>
<br/>Air date: Fri May 15 00:00:00 UTC 1998<br/>Duration: 48:51<br/>Rating: 4.0 / 5.0<br/>Added to queue at 05:32AM on Nov 29, 2010<br/>
</p>

			 * The idea here is to split on paragraph seperators and grab the first actual paragraph
			 * Regular expresions might be easier here, but I have a hunch this is a little faster.
			 * This might be a case wher I'm micro-perfing for no reason
			 */

			string baseDescription = xml.Descendants("description").First().Value;
			var descriptionParagraphs = baseDescription.Split(new string[] { "p>" }, StringSplitOptions.RemoveEmptyEntries);
			return HttpUtility.HtmlDecode(descriptionParagraphs[1].Substring(0, descriptionParagraphs[1].Length - 2));

		}
	}
}
